package com.example.testdb1.handle;

import com.example.testdb1.constant.MessageConstant;
import com.example.testdb1.entity.result.R;
import com.example.testdb1.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {


    @ExceptionHandler
    public R exception(BaseException e) {
        log.error("异常信息：{}", e.getMessage());
        return R.error(e.getMessage());
    }

    @ExceptionHandler
    public R duplicateSql(SQLIntegrityConstraintViolationException e) {
        String message = e.getMessage();
        log.error("异常信息:{}", message);
        //实体类唯一约束异常处理
        if (message.contains("Duplicate entry")) {
            String[] split = message.split(" ");
            String sName = split[2];
            String messageResult = "添加失败，用户" + sName + MessageConstant.ELREADY_EXIST;

            return R.error(messageResult);
        } else {
            return R.error(message);
        }
    }
}
